package com.sample.springbatch.scheduler;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.*;

/**
 * 调度服务监控
 * 通过AOP监控方法的执行情况，和异常情况
 *
 * @author zwg
 * @date 2019-05-21 18:01
 **/
@Component
@Aspect
public class ScheduledServiceHandler {

    Logger logger = LoggerFactory.getLogger(ScheduledServiceHandler.class);

    @Pointcut("@annotation(org.springframework.scheduling.annotation.Scheduled)")
    public void proxyAspect() {

    }

    @Around("proxyAspect()")
    public Object doInvoke(ProceedingJoinPoint joinPoint) throws Throwable{
        Date date = new Date();
        String message = "ok";
        SchedulerLog schedulerLog = new SchedulerLog("",joinPoint.getTarget().getClass().getName(),getLocalIp().toString(),date);
        Object result = null;
        try{
            result = joinPoint.proceed();
        }catch (Exception e){
            message = e.getMessage();
            logger.error("doInvoke error:",e);
        }
        schedulerLog.end(message,new Date());
        logger.info("{}",schedulerLog);
        return result;
    }


    /**
     * 取得本机IP
     * @return
     */
    private Set<String> getLocalIp(){
        Set<String> ipSet = new HashSet<>();
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            while(interfaces.hasMoreElements()){
                NetworkInterface ni = interfaces.nextElement();
                Enumeration<InetAddress> address = ni.getInetAddresses();
                while (address.hasMoreElements()){
                    InetAddress next = address.nextElement();
                    if(next!=null && next instanceof Inet4Address) {
                        ipSet.add(next.getHostAddress());
                    }
                }
            }
        } catch (SocketException e) {
            logger.error("",e);
        }
        return ipSet;
    }


//    @AfterThrowing(pointcut="proxyAspect()",throwing="ex")
//    public void doException(JoinPoint joinPoint, Exception ex){
//        Date date = new Date();
//        Object target = joinPoint.getTarget();
//        logger.error("doException className:"+joinPoint.getTarget().getClass().getName()+",start:"+date+",error:",ex);
//    }

}
